import React, { useState } from 'react';
import { Button, Table } from 'antd';
import axios from "axios"
import { useEffect } from 'react';
const columns = [
  {
    title: 'id',
    dataIndex: 'id',
  },
  {
    title: 'Name',
    dataIndex: 'name',
  },
];



const App = () => {
  const [data,setData] = useState([]);
  const [page,setPage] = useState(1)
  const [total,setTotal] = useState(0)
  function getList(){
    axios.get(`/api/${page}`).then(r=>{
      console.log(r.data.list)
      setData(r.data.list)
      setTotal(r.data.total)
    })
  }
  useEffect(()=>{
    getList()
  },[page])
  const [selectedRowKeys, setSelectedRowKeys] = useState([2,4,5,6,7,1,3,8,11,12,13]);
  const [loading, setLoading] = useState(false);
  const start = () => {
    setLoading(true);
    // ajax request after empty completing
    setTimeout(() => {
      setSelectedRowKeys([]);
      setLoading(false);
    }, 1000);
  };
  const onSelectChange = (newSelectedRowKeys) => {
    setSelectedRowKeys(pre=>Array.from(new Set([...pre,...newSelectedRowKeys])));
  };
  
  const onSingleSelect =(record, selected, selectedRows, nativeEvent)=>{
    console.log(selected)
    console.log(record.id)
    console.log(selectedRowKeys)
    const newSelected = !selected&&selectedRowKeys.filter(v=>v===record.id)
    // console.log(newSelected)
    newSelected&&setSelectedRowKeys([...newSelected]);
  }
  const onSelectAll = (selected, selectedRows, changeRows)=>{
    console.log(selected, selectedRows, changeRows)
  }
  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
    onSelect:onSingleSelect,
    onSelectAll:onSelectAll
  };
  

  const onPageChange = (v)=>{
    setPage(v)
  }
  const hasSelected = selectedRowKeys.length > 0;
  return (
    <div>
      {selectedRowKeys.toString()}
      <div
        style={{
          marginBottom: 16,
        }}
      >
        <Button type="primary" onClick={start} disabled={!hasSelected} loading={loading}>
          Reload
        </Button>
        <span
          style={{
            marginLeft: 8,
          }}
        >
          {hasSelected ? `Selected ${selectedRowKeys.length} items` : ''}
        </span>
      </div>
      <Table rowKey="id" pagination={{total:total,onChange:onPageChange}} rowSelection={rowSelection} columns={columns} dataSource={data} />
    </div>
  );
};
export default App;